// 用于存储实例化后 WebSocket
import {ElMessage} from "element-plus";
import {Ref, UnwrapRef} from "vue";

let websocket: WebSocket | null = null;

// 创建websocket
const creatWebSocket = (wsUrl: string, msgList: Ref<UnwrapRef<any[]>>) => {
    // 判断当前浏览器是否支持 WebSocket
    if (!("WebSocket" in window || "MozWebSocket" in window)) {
        ElMessage.error("当前浏览器不支持当前连接方式，请更换浏览器或连接方式!")
        return
    }

    // 初始化连接
    initWebSocket(wsUrl, msgList);
}

// 初始化websocket
const initWebSocket = (wsUrl: string, msgList: Ref<UnwrapRef<string[]>>) => {
    websocket = new WebSocket(wsUrl);
    console.log("websocket:", websocket);

    // 开启
    websocket.onopen = function () {
        ElMessage.success({
            showClose: true,
            grouping: true,
            message: "服务器连接成功!",
        })
    };

    // 接收
    websocket.onmessage = function (e: MessageEvent<any>) {
        msgList.value.push(JSON.parse(e.data));
    };


    // 连接发生错误
    websocket.onerror = function () {
        ElMessage.error({
            showClose: true,
            grouping: true,
            message: "服务器连接错误!",
        })
    };


    websocket.onclose = function (e) {
        console.log(e);
        ElMessage.success({
            showClose: true,
            grouping: true,
            message: "服务器连接已关闭!",
        })
    };
}

// 发送
const send = (data: any) => {
    // 检查连接状态
    if (!websocket || websocket.readyState !== 1) {
        ElMessage.error({
            showClose: true,
            grouping: true,
            message: "未连接服务器!",
        })
        return;
    }
    websocket.send(JSON.stringify(data));
}

// 关闭
const close = () => {
    // 检查连接状态
    if (!websocket || websocket.readyState !== 1) {
        ElMessage.error({
            showClose: true,
            grouping: true,
            message: "未连接服务器!",
        })
        return;
    }
    websocket.close();
};

export {
    creatWebSocket,
    send,
    close,
};
